﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
/// <summary>
///SqlHelper 的摘要说明
/// </summary>
public class SqlHelper
{
    private string connStr = string.Empty;
    private SqlConnection con = null;
    private SqlCommand cmd = null;
    private SqlDataAdapter da = null;
    //private SqlDataReader reader = null;
    public SqlHelper()
    {
        connStr = WebConfigurationManager.ConnectionStrings["conn"].ConnectionString;
    }
    /// <summary>
    /// 获取数据库的连接
    /// </summary>
    /// <returns></returns>
    public SqlConnection GetSqlConnection()
    {
        return con = new SqlConnection(connStr);
    }
    /// <summary>
    /// 打开数据库连接
    /// </summary>
    /// <param name="con">数据库连接</param>
    public void OpenConnection(SqlConnection con)
    {
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
    }
    /// <summary>
    /// 关闭连接
    /// </summary>
    /// <param name="con">数据库连接</param>
    public void CloseConnection(SqlConnection con)
    {
        if (con.State == ConnectionState.Open)
        {
            con.Close();
        }
    }
    /// <summary>
    /// 获取数据库的只向前读取游标
    /// </summary>
    /// <param name="sqlStr">sql语句</param>
    /// <param name="con">数据库连接</param>
    /// <returns></returns>
    public SqlDataReader GetSqlDataReader(string sqlStr, SqlConnection con)
    {
        cmd = new SqlCommand(sqlStr, con);
        this.OpenConnection(con);
        return  cmd.ExecuteReader();
       
    }
    /// <summary>
    /// 返回查询结果的第一行结果
    /// </summary>
    /// <param name="sqlStr">sql语句</param>
    /// <param name="con">数据库连接</param>
    /// <returns></returns>
    public object GetExecuteScalar(string sqlStr, SqlConnection con)
    {
        cmd = new SqlCommand(sqlStr, con);
        this.OpenConnection(con);
        return cmd.ExecuteScalar();
    }
}